package com.gitee.yongzhuzl.commonutil.util.request;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * description: HTTP请求相关工具类
 * @author 朱正磊
 * @date 2023-07-11 18:01:07
 */
public class RequestUtil {

    private static final Logger log = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * description: 获取当前请求线程的HTTP请求对象
     * @author 朱正磊
     * @date 2023-07-11 18:03:04
     * @return 返回HTTP请求对象
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        assert servletRequestAttributes != null;
        return servletRequestAttributes.getRequest();
    }

    /**
     * description: 根据参数名获取参数值
     * @author 朱正磊
     * @date 2023-07-11 18:37:28
     * @param name 参数名
     * @return 返回参数值
     */
    public static String getParameter(String name) {
        String parameter = getRequest().getParameter(name);
        log.info("根据参数名【{}】获取到的参数值【{}】", name, parameter);
        return parameter;
    }

    /**
     * description: 根据请求头名获取请求头值
     * @author 朱正磊
     * @date 2023-07-11 18:42:58
     * @param name 请求头名
     * @return 返回请求头值
     */
    public static String getHeader(String name) {
        String header = getRequest().getHeader(name);
        log.info("根据请求头名【{}】获取到的请求头值【{}】", name, header);
        return header;
    }

}
